import java.io.IOException;
import java.util.Set;
import java.util.logging.FileHandler;
import java.util.logging.Logger;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;


public class ConnectingThreadJava extends Thread{
	private final int MAX_CONNECTIONS = 50;
	
	private StreamConnectionNotifier strmNotf;
	private Set<ConnectedThreadJava> threads;
	
	private Logger logger;
	private FileHandler fh;
	private String url;
	private boolean continua = true;
	
	public ConnectingThreadJava(StreamConnectionNotifier strmNotf_p,
			Set<ConnectedThreadJava> threads_p,
			String url_p){

		strmNotf = strmNotf_p;
		threads = threads_p;
		url = url_p;
		
		//Initialize logger
		logger = Logger.getLogger("pckt.Test-ConnectedThreadJava");
		try {
			fh = new FileHandler("LogConnectingThread.txt");
		} catch (Exception e) {
			logger.warning("Couldn't open file handler for logger: ConnectingThreadJava");
		} 
		logger.addHandler(fh);
		
		
		try {
			strmNotf = (StreamConnectionNotifier) Connector.open(url);
		} catch (IOException e) {
			logger.warning("Couldn't set this device to be a server.");
			System.exit(0);
		}

	}

	@Override
	public void run(){
		int nomeArq = 0;
		StreamConnection[] strmConn = new StreamConnection[MAX_CONNECTIONS];
		ConnectedThreadJava t[] = new ConnectedThreadJava[1024];
		while (continua){
			try {
				System.out.println("Waiting for income connection.");
				strmConn[nomeArq] = strmNotf.acceptAndOpen();
				System.out.println("Accepted");
				
			} catch (Exception e) {
				logger.warning("Couldn't accept a connection.");
				return;
			}
			t[nomeArq] = new ConnectedThreadJava(strmConn[nomeArq], nomeArq);
			threads.add(t[nomeArq]);
			t[nomeArq++].start();
			//PcktPC.sendFile(t, "out.txt");
		}
	}
	
	public void close(){
		try {
			strmNotf.close();
		} catch (IOException e) {}
		continua = false;
	}
}
